using MediatR;
using RBAC.Domain.Department;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Write.Api.Application.Command.ERP.MaterialFile.Department;
using System.Transactions;
using Microsoft.Extensions.Logging;

namespace RBAC.Write.Api.Application.Handler.ERP.MaterialFile.Department
{
    /// <summary>
    /// 删除部门处理类 - 实现逻辑删除
    /// </summary>
    public class DeleteDepartmentHandler : IRequestHandler<DeleteDepartmentCommand, APIResult<int>>
    {
        private readonly IBaseRepository<DepartmentManagement> departmentRepository;
        private readonly ILogger<DeleteDepartmentHandler> logger;

        public DeleteDepartmentHandler(
            IBaseRepository<DepartmentManagement> departmentRepository,
            ILogger<DeleteDepartmentHandler> logger)
        {
            this.departmentRepository = departmentRepository;
            this.logger = logger;
        }

        /// <summary>
        /// 逻辑删除部门
        /// </summary>
        /// <param name="request">删除部门请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public Task<APIResult<int>> Handle(DeleteDepartmentCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> res = new APIResult<int>();

            try
            {
                logger.LogInformation("开始逻辑删除部门，部门ID: {DepartmentId}", request.Id);

                // 1. 检查部门是否存在且未被删除
                var department = departmentRepository.QueryFirstOrDefault<DepartmentManagement>(
                    "SELECT * FROM Department WHERE Id = @Id AND IsDeleted = false", 
                    new { Id = request.Id });

                if (department == null)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "部门不存在或已被删除";
                    logger.LogWarning("部门不存在或已被删除，ID: {DepartmentId}", request.Id);
                    return Task.FromResult(res);
                }

                logger.LogInformation("找到部门: {DepartmentName} (ID: {DepartmentId})", 
                    department.DepartmentName, department.Id);

                // 2. 检查是否有子部门
                var childCount = departmentRepository.QueryFirstOrDefault<int>(
                    "SELECT COUNT(1) FROM Department WHERE ParentId = @ParentId AND IsDeleted = false", 
                    new { ParentId = request.Id });

                if (childCount > 0)
                {
                    res.Code = APIEnums.Error;
                    res.Msg = "该部门下存在子部门，无法删除";
                    logger.LogWarning("部门删除失败：存在子部门，父部门ID: {DepartmentId}, 子部门数量: {ChildCount}", 
                        request.Id, childCount);
                    return Task.FromResult(res);
                }

                // 3. 使用事务执行逻辑删除
                using (TransactionScope tran = new TransactionScope())
                {
                    try
                    {
                        // 执行逻辑删除：将IsDeleted设置为true
                        var sql = "UPDATE Department SET IsDeleted = true WHERE Id = @Id AND IsDeleted = false";
                        var affectedRows = departmentRepository.Execute(sql, new { Id = request.Id });

                        if (affectedRows <= 0)
                        {
                            res.Code = APIEnums.Error;
                            res.Msg = "部门删除失败，可能部门不存在或已被删除";
                            logger.LogWarning("部门删除失败：未找到可删除的部门，ID: {DepartmentId}", request.Id);
                            return Task.FromResult(res);
                        }

                        tran.Complete();

                        res.Code = APIEnums.Success;
                        res.Data = affectedRows;
                        res.Msg = "部门删除成功";

                        logger.LogInformation("部门 {DepartmentName} (ID: {DepartmentId}) 逻辑删除完成", 
                            department.DepartmentName, department.Id);
                    }
                    catch (Exception ex)
                    {
                        logger.LogError(ex, "删除部门过程中发生错误: {Message}", ex.Message);
                        res.Code = APIEnums.Error;
                        res.Msg = "删除部门失败";
                        res.Data = 0;
                        throw;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "删除部门失败: {Message}", ex.Message);
                res.Code = APIEnums.Error;
                res.Msg = "删除部门失败";
                res.Data = 0;
            }

            return Task.FromResult(res);
        }
    }
}